<template>
  <div class="warpper-box">
    <form-create v-model="params.fApi" :rule="params.rule" :option="params.option" @btn-search-click="onSearch"
      @btn-reset-click="reset" />
    <a-button type='primary' icon="plus" @click="$refs.createInfo.add(true, 0)">新增</a-button>
    <a-button type='primary' icon="file-excel" @click="enterpriseExport">导出</a-button>

    <s-table ref="table" showQuickJumper row-key="id" showPagination="auto" size="default" :columns="columns" :data="loadData"
      :scroll="{ x: 2000 }">
      <span slot="loginAccountStatus" slot-scope="text, record">
        <a-switch :defaultChecked="text == 1" @change="(text) => loginChange(text, record.enterpriseId)" />
      </span>
      <!-- <span slot="isPublic" slot-scope="text, record">
        <a-switch :defaultChecked="text == 1" @change="(text)=>publicChange(text,record.enterpriseId)" />
      </span> -->
      <!-- 操作栏 -->
      <span slot="action" slot-scope="text, record">
        <a @click="$refs.createInfo.add(record, 1)">编辑</a>
        <a-divider type="vertical" />
        <a @click="$refs.createInfo.add(record, 2)">费用设置</a>
        <a-divider type="vertical" />
        <a @click="openPunter(record)">客户经理设置</a>
        <a-divider type="vertical" />
        <a @click="openCooperate(record)">合作状态调整</a>
        <a-divider type="vertical" />
        <a-popconfirm title="确认删除?" ok-text="确认" cancel-text="取消" @confirm="remove(record)">
          <a>删除</a>
        </a-popconfirm>
      </span>
    </s-table>
    <add-info ref="createInfo" @on-ok="addLoad" />
    <!-- 合作状态 -->
    <a-modal v-model="cooperateVisible" title="合作状态调整" @ok="editCooperate">
      <a-select v-model="cooperateStatus" style="width: 240px;">
        <a-select-option :key="1">
          待开始合作
        </a-select-option>
        <a-select-option :key="2">
          合作中
        </a-select-option>
        <a-select-option :key="3">
          合作暂停
        </a-select-option>
        <a-select-option :key="4">
          合作终止
        </a-select-option>
      </a-select>
    </a-modal>
    <!-- 客户经理 -->
    <a-modal v-model="punterVisible" title="客户经理设置" @ok="editPunter">
      <a-form-item label="客户经理">
        <a-tree-select v-model="punterIds" tree-checkable :tree-data="orgList" multiple placeholder="选择客户经理"
          style="width: 300px;" :replace-fields="{ value: 'orgId', title: 'orgName', children: 'children' }" />
      </a-form-item>
    </a-modal>
  </div>
</template>

<script>
import {
  STable
} from '@/components'
import {
  getEnterprisePage,
  delEnterprise,
  getEnterpriseExport,
  enterprisePublicSet,
  enterpriseLoginAccountStatusSet,
  enterpriseCooperateStatusSet,
  updatePublic,
  enterprisePublic
} from "@/api/human/enterprise"
import {
  PARAMS_ENTERPRISE,
  COLUMNS_ENTERPRISE
} from "./form"
import { mapGetters, mapActions } from 'vuex'
import {
  OPTION_BLOCK,
  OPTION_INLINE
} from "../base_form"
import AddInfo from "./enterprise_add"
import {
  getOrgLists
} from "@/api/human/department"
export default {
  name: 'enterpriseList',
  components: {
    STable,
    AddInfo
  },
  data() {
    return {
      params: {
        fApi: {},
        rule: PARAMS_ENTERPRISE,
        option: OPTION_INLINE
      },
      columns: COLUMNS_ENTERPRISE,
      loadData: parameter => {
        let formdata = this.params.fApi.formData();
        return getEnterprisePage(Object.assign(parameter, formdata)).then(res => {
          return {
            pageNo: res.data.number,
            pageSize: res.data.size,
            totalCount: res.data.total,
            totalPage: Math.ceil(res.data.total / 10),
            data: res.data.content
          }
        })
      },
      cooperateVisible: false, // 合作状态显示
      cooperateStatus: 0, // 合作状态
      punterVisible: false, // 客户经理显示
      punterIds: [], // 客户经理选中项
      orgList: [], // 所有部门人员
      enterpriseId: "", // 当前企业id

      selectedRowKeys: [],
      selectedRows: []
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
  },
  filters: {

  },
  mounted() {
    window.addEventListener('keyup', this.keyDown);
  },
  destroyed() {
    window.removeEventListener('keyup', this.keyDown);
  },
  beforeCreate() {
    this.events_form = this.$form.createForm(this, {
      name: 'events_form'
    })
  },
  created() {

  },
  methods: {
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    keyDown(e) {
      if (e.keyCode == 13) {
        this.$refs.table.refresh(true);
      }
    },
    addLoad(state) {
      this.$refs.table.refresh(state);
    },
    async publicChange(check, id) {
      let isOpen = 0;
      if (check) {
        isOpen = 1
      }
      const {
        code
      } = await enterprisePublicSet({
        isPublic: isOpen,
        enterpriseId: id
      });
      if (code == '1') {
        this.$message.success('操作成功');
        this.$refs.table.refresh(true);
      }
    },
    async loginChange(check, id) {
      let isOpen = 2;
      if (check) {
        isOpen = 1
      }
      const {
        code
      } = await enterpriseLoginAccountStatusSet({
        loginAccountStatus: isOpen,
        enterpriseId: id
      });
      if (code == '1') {
        this.$message.success('操作成功');
        this.$refs.table.refresh(true);
      }
    },
    async remove(item) {
      let params = {
        id: item.id
      }
      const {
        code
      } = await delEnterprise(params);
      if (code === '1') {
        this.$message.success('操作成功');
        this.$refs.table.refresh(true);
      }
    },
    enterpriseExport() {
      let formdata = this.params.fApi.formData();
      getEnterpriseExport(formdata).then(res => {
        const blob = new Blob([res]);
        const fileName = '企业列表.xlsx';
        const elink = document.createElement('a'); // 创建a标签
        elink.download = fileName;
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click(); // 点击下载
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink); // 释放标签
      })
    },
    // 打开客户经理
    openPunter(rows) {
      this.punterVisible = true;
      this.enterpriseId = rows.enterpriseId;
      this.getOrgList();
      this.getEnterprisePublic();
    },
    // 获取客户经理id
    async getEnterprisePublic() {
      const {code,data} = await enterprisePublic(this.enterpriseId);
      if (code == '1') {
        this.punterIds = data.map(item => item.staffId);
      }
    },
    // 客户经理设置
    async editPunter() {
      if (this.punterIds.length == 0) {
        return this.$message.warning('请选择客户经理')
      }
      const {
        code
      } = await updatePublic({
        staffIdList: this.punterIds,
        enterpriseId: this.enterpriseId
      });
      if (code == '1') {
        this.punterVisible = false;
        this.$message.success('操作成功');
        this.$refs.table.refresh(true);
      }
    },
    // 获取部门所有人员
    async getOrgList() {
      const {
        code,
        data
      } = await getOrgLists({ parentOrgId: -1 });
      if (code === '1') {
        this.orgList = this.matterTree(data,1)
        // console.log(this.orgList);
      }
    },
    // 处理部门所有人员状态
    matterTree(data) {
      for (var i = 0; i < data.length; i++) {
        // 这里面就是你处理数据的地方 
        // let idStr = Date.now().toString(36)
        // idStr += Math.random().toString(36).substr(2)
        if (data[i].children && data[i].children.length > 0) {
          // children若不为空数组，则继续 递归调用 本方法
          this.matterTree(data[i].children)
        }
      }
      return data
    },
    // 打开合作状态
    openCooperate(rows) {
      this.cooperateVisible = true;
      this.cooperateStatus = rows.cooperateStatus;
      this.enterpriseId = rows.enterpriseId;
    },
    // 合作状态调整
    async editCooperate() {
      const {
        code
      } = await enterpriseCooperateStatusSet({
        cooperateStatus: this.cooperateStatus,
        enterpriseId: this.enterpriseId
      });
      if (code == '1') {
        this.cooperateVisible = false;
        this.$message.success('操作成功');
        this.$refs.table.refresh(true);
      }
    },
    onSearch() {
      this.$refs.table.refresh(true);
      // this.selectedRowKeys = [];
      // this.selectedRows = [];
    },
    reset() {
      this.events_form.resetFields();
      this.$refs.table.refresh(true);
    }
  }
}
</script>
